package com.sparkflow.mysqlbinlog.clickhousesync.service.position;

import com.sparkflow.mysqlbinlog.clickhousesync.utils.JsonUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Binlog位置管理服务
 * 负责管理和持久化MySQL Binlog位置信息，支持断点续传
 *
 * @author Mr_xiaoZH
 * @date 2025-07-23
 */
public class BinlogPositionService {
    private static final String POSITION_FILE = "binlog_position.json";

    public static BinlogPosition load() {
        try {
            if (Files.exists(Paths.get(POSITION_FILE))) {
                String content = new String(Files.readAllBytes(Paths.get(POSITION_FILE)));
                if(StringUtils.isBlank(content)){
                    return null;
                }
                return JsonUtil.jsonDeserialization(content, BinlogPosition.class);
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to load binlog position", e);
        }
    }

    public static void savePosition(BinlogPosition position) {
        try {
            Files.write(
                    Paths.get(POSITION_FILE),
                    JsonUtil.jsonSerialization(position).getBytes()
            );
        } catch (IOException e) {
            throw new RuntimeException("Failed to save binlog position", e);
        }
    }

    @Getter
    @Setter
    @NoArgsConstructor
    public static class BinlogPosition {
        private String filename;
        private long position;

        public BinlogPosition(String filename, long position) {
            this.filename = filename;
            this.position = position;
        }
    }
}
